﻿using AutoMapper;
using BS.Domain.traceability;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.ComponentModel;

namespace BS.Read.Api.Handler.Tranceabilty
{
    public class ShowTranceListCommandHandler : IRequestHandler<GetTranceShuoYuanCommand, ApiResult>
    {
        private readonly ItraceabilitableRepository _traceabilitableRepository;

        private readonly IMapper _mapper;

        private readonly ILogger<ShowTranceListCommandHandler> _logger;

        private readonly IGoodsRepository _goodsRepository;

        public ShowTranceListCommandHandler(ItraceabilitableRepository traceabilitableRepository, IMapper mapper, ILogger<ShowTranceListCommandHandler> logger, IGoodsRepository goodsRepository)
        {
            _traceabilitableRepository = traceabilitableRepository;
            _mapper = mapper;
            _logger = logger;
            _goodsRepository = goodsRepository;
        }

        public async Task<ApiResult> Handle(GetTranceShuoYuanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var tranceList =(await _traceabilitableRepository.GetAllAsync(x=>x.IsDeleted==false)).AsQueryable();

                var goodsList= (await _goodsRepository.GetAllAsync()).AsQueryable();
                if (!string.IsNullOrEmpty(request.GoodsName))
                {
                    goodsList = goodsList.Where(x => x.GoodsName.Contains(request.GoodsName));
                }
                if (!string.IsNullOrEmpty(request.Productionbatches))
                {
                    tranceList = tranceList.Where(x => x.Productionbatches.Contains(request.Productionbatches));
                }
                if (request.ShelflifeDay>0)
                {
                    tranceList = tranceList.Where(x => x.ShelflifeDay == request.ShelflifeDay);
                }
                if (!string.IsNullOrEmpty(request.Productionlicense))
                {
                    tranceList = tranceList.Where(x => x.Productionlicense.Contains(request.Productionlicense));
                }
                if (!string.IsNullOrEmpty(request.ProductionCompany))
                {
                    tranceList = tranceList.Where(x => x.ProductionCompany.Contains(request.ProductionCompany));
                }
                var list=from traceabilitable in tranceList
                         join Goods in goodsList on traceabilitable.GoodsId equals Goods.GoodsId
                         select new GetTranceShuoYuanCommandPonse
                         {
                             TrId = traceabilitable.TrId,
                             GoodsId = Goods.GoodsId,
                             Productionbatches = traceabilitable.Productionbatches,
                             ShelflifeDay = traceabilitable.ShelflifeDay,
                             Productionlicense = traceabilitable.Productionlicense,
                             ProductionCompany = traceabilitable.ProductionCompany,
                             Coverimage = traceabilitable.Coverimage,
                             GoodsName = Goods.GoodsName
                         };
                var page = new PagingResult
                {
                    totalCount = list.Count(),
                    totalPage = (int)Math.Ceiling((decimal)list.Count()/request.PageSize),
                    List = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList()
                };
                return await Task.FromResult(ApiResult.Ok(page));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "ShowTranceListCommandHandler");
                return await Task.FromResult(ApiResult.Fail(ex.Message));
            }
        }
    }
}
public class GetTranceShuoYuanCommand:IRequest<ApiResult>
{
    [DefaultValue(1)]
    public int PageIndex { get; set; }
    [DefaultValue(2)]
    public int PageSize { get; set; }

    /// <summary>
    /// 商品外键
    /// </summary>
    public string? GoodsName { get; set; }

    /// <summary>
    /// 生产批次
    /// </summary>
    public string? Productionbatches { get; set; }

    /// <summary>
    /// 保质期（天）
    /// </summary>
    public int ShelflifeDay { get; set; }

    /// <summary>
    /// 生产许可证
    /// </summary>
    public string? Productionlicense { get; set; }

    /// <summary>
    /// 生产企业
    /// </summary>
    public string? ProductionCompany { get; set; }
}
public class GetTranceShuoYuanCommandPonse
{
    public int TrId { get; set; }
    /// <summary>
    /// 商品外键
    /// </summary>
    public int GoodsId { get; set; }
    /// <summary>
    /// 生产批次
    /// </summary>
    public string Productionbatches { get; set; } = string.Empty;
    /// <summary>
    /// 保质期（天）
    /// </summary>
    public int ShelflifeDay { get; set; }
    /// <summary>
    /// 生产许可证
    /// </summary>
    public string Productionlicense { get; set; } = string.Empty;
    /// <summary>
    /// 生产企业
    /// </summary>
    public string ProductionCompany { get; set; } = string.Empty;
    /// <summary>
    /// 封面图
    /// </summary>
    public string Coverimage { get; set; } = string.Empty;

    public string GoodsName { get; set; } = string.Empty;
}